package com.example.android.ouactivity.adapter;
/*
 * Created by kelion on 2016/11/14.
 */

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.android.ouactivity.R;
import com.example.android.ouactivity.model.News;
import com.example.android.ouactivity.utils.ImgLoader;

import java.util.List;

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolder>  {

    private LayoutInflater mLayoutInflater;
    private OnItemClickListener mOnItemClickListener;
    public List<News> newsList;
    private ImgLoader  mImageLoader;

    //设置一开始加载的数据
    public RecyclerViewAdapter(Context mContext, List<News> newsList) {
        this.newsList = newsList;
        mLayoutInflater = LayoutInflater.from(mContext);
        mImageLoader = new ImgLoader();

    }

    //创建ViewHolder
    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View mView = mLayoutInflater.inflate(R.layout.item_main, parent, false);
        return new RecyclerViewHolder(mView);
    }


    //绑定ViewHoler，给item中的控件设置数据
    @Override
    public void onBindViewHolder(final RecyclerViewHolder holder, @SuppressLint("RecyclerView") final int position) {
        if (mOnItemClickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override public void onClick(View v) {
                    mOnItemClickListener.onItemClick(holder.itemView, position);
                }
            });

            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override public boolean onLongClick(View v) {
                    mOnItemClickListener.onItemLongClick(holder.itemView, position);
                    return true;
                }
            });
        }

        News news = newsList.get(position);
        holder.mTextView.setText(news.getTitle());

        String pic_url = news.getCover();

        //避免缓存的标签
        holder.ivPic.setTag(pic_url);

        mImageLoader.showImageByAsyncTask(holder.ivPic,pic_url);
    }




    public interface OnItemClickListener {
        void onItemClick(View view, int position);
        void onItemLongClick(View view, int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    @Override
    public int getItemCount() {
        return newsList.size();
    }
}
